using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using RBAC.ErrorCode;
using SmartHealthcare.Write.Api.Application.Command.Payment;
using System;
using System.IO;
using System.Threading.Tasks;

namespace SmartHealthcare.Write.Api.Controllers
{
    /// <summary>
    /// 支付记录写入控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PaymentRecordController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<PaymentRecordController> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public PaymentRecordController(IMediator mediator, ILogger<PaymentRecordController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 创建支付记录
        /// </summary>
        /// <param name="command">创建支付记录命令</param>
        /// <returns>新创建的支付记录ID</returns>
        [HttpPost]
        public async Task<APIResult<long>> CreatePaymentRecord([FromBody] CreatePaymentRecordCommand command)
        {
            logger.LogInformation($"接收到创建支付记录请求，患者：{command.PatientName}，金额：{command.Amount}");
            return await mediator.Send(command);
        }

        /// <summary>
        /// 上传支付凭证
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <param name="file">凭证文件</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/receipt")]
        public async Task<IActionResult> UploadReceipt(long id, IFormFile file)
        {
            logger.LogInformation($"接收到上传支付凭证请求，支付记录ID：{id}");

            if (file == null || file.Length == 0)
            {
                return BadRequest("未提供有效的凭证文件");
            }

            try
            {
                // 生成文件保存路径
                var fileName = $"{id}_{DateTime.Now:yyyyMMddHHmmss}{Path.GetExtension(file.FileName)}";
                var filePath = Path.Combine("wwwroot", "receipts", fileName);
                var directoryPath = Path.GetDirectoryName(filePath);

                // 确保目录存在
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 更新支付记录中的凭证URL
                var updateCommand = new UpdatePaymentReceiptCommand
                {
                    Id = id,
                    ReceiptUrl = $"/receipts/{fileName}",
                    OperatorName = User.Identity?.Name ?? "system"
                };
                
                var updateResult = await mediator.Send(updateCommand);
                
                if (updateResult.Code != APIEnums.Success)
                {
                    logger.LogWarning($"更新支付凭证URL失败：{updateResult.Msg}");
                }

                // 返回成功结果
                return Ok(new { filePath = $"/receipts/{fileName}" });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"上传支付凭证时发生异常，支付记录ID：{id}");
                return StatusCode(500, $"上传凭证失败：{ex.Message}");
            }
        }
    }
} 